package com.zxh.blog.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.zxh.blog.R
import com.zxh.blog.activity.ArticleDetailActivity
import com.zxh.blog.activity.SearchActivity
import com.zxh.blog.adapter.ArticleRecyclerAdapter
import com.zxh.blog.bean.Article
import com.zxh.blog.bean.PageArticle
import com.zxh.blog.bean.ResponseJson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class HomeFragment : Fragment() {

    private lateinit var mRecyclerView: RecyclerView

    private lateinit var mAdapter: ArticleRecyclerAdapter

    // 搜索框
    private lateinit var mSearch: LinearLayout

    // 加号按钮
    private lateinit var mAddBtn: ImageButton

    private var mArticleList = ArrayList<Article>()

    private val mBaseURL = "http://43.140.201.43:7777/article/articleList?pageNum=1&pageSize=5&categoryId=0"

    private var mRefreshFlag = false

    private var mPageNum = 1
    @SuppressLint("MissingInflatedId")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        // 调用后端接口接收并解析json数据
        initDataByOkhttp(mBaseURL)
        // 初始化RecyclerView
        mRecyclerView = view.findViewById(R.id.articleList)
        // 初始化适配器
        mAdapter = ArticleRecyclerAdapter(requireContext())
        // 初始化控件
        mSearch = view.findViewById(R.id.search_layout)
        mAddBtn = view.findViewById(R.id.add_article)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG, "onViewCreated: ")
        // 找到 SmartRefreshLayout 组件
        val refreshLayout = view.findViewById<SmartRefreshLayout>(R.id.refreshLayout)
        refreshLayout.setRefreshHeader(ClassicsHeader(context))
        refreshLayout.setRefreshFooter(ClassicsFooter(context))
        // 设置下拉刷新监听器
        refreshLayout.setOnRefreshListener {
            // 从服务器加载最新数据
            mRefreshFlag = true
            mPageNum = 1
            initDataByOkhttp(mBaseURL)
            refreshLayout.finishRefresh()
        }
        // 设置上拉加载监听器
        refreshLayout.setOnLoadMoreListener {
            var url = ""
            // 从服务器加载更多数据
            if (mRefreshFlag) {
                mPageNum++
                url = "http://43.140.201.43:7777/article/articleList?pageNum=$mPageNum&pageSize=5&categoryId=0"
                mPageNum = 2
                mRefreshFlag = false
            } else {
                mPageNum++
                url = "http://43.140.201.43:7777/article/articleList?pageNum=$mPageNum&pageSize=5&categoryId=0"
            }
            loadDataByOkhttp(url)
            refreshLayout.finishLoadMore()
        }

        // 跳转到搜索页面
        mSearch.setOnClickListener {
            startActivity(Intent(context, SearchActivity::class.java))
        }
    }

    override fun onStart() {
        super.onStart()
        // 设置item点击事件
        mAdapter.setClickListener(object : ArticleRecyclerAdapter.ClickListener{
            override fun onClick(position: Int, articleList: ArrayList<Article>) {
                val article = articleList[position]
                val id = article.id
                // 跳转到文章详情页面
                jumpToArticleDetailWebView(id)
            }
        })
    }

    /**
     *  上拉加载操作
     */
    private fun loadDataByOkhttp(url: String) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                    // 将UI更新操作移动到主线程
                    Handler(Looper.getMainLooper()).post {
                        // 更新数据
                        updateLoadData()
                    }
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    /**
     *  上拉加载得到数据后更新UI视图
     */
    private fun updateLoadData() {
        mAdapter.update(mArticleList)
    }

    companion object {
        private const val TAG = "HomeFragment"
    }

    /**
     *  根据文章id调转到对应的文章详情页面
     */
    private fun jumpToArticleDetailWebView(id: String) {
        val intent = Intent(requireContext(), ArticleDetailActivity::class.java)
        intent.putExtra("articleId", id)
        startActivity(intent)
    }

    /**
     *  使用okhttp请求后端接口获取json对象
     */
    private fun initDataByOkhttp(url: String) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                    // 将UI更新操作移动到主线程
                    Handler(Looper.getMainLooper()).post {
                        // 更新UI视图
                        updateUI()
                    }
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    /**
     *  使用gson解析
     */
    private fun parseJSONWithGSON(responseData: String) {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<PageArticle<Article>>>() {}.type
        val data: ResponseJson<PageArticle<Article>> = gson.fromJson(responseData, typeToken)
        mArticleList = data.data?.rows as ArrayList<Article>
        // 创建一个临时的文章列表，用于存储截取summary后的Article对象
        val articleList = ArrayList<Article>()
        for (article in mArticleList) {
            // 限制summary（文章摘要）的字符长度为40
            if (article.summary.length > 40) {
                article.summary = article.summary.substring(0, 40) + "..."
            }
            articleList.add(article)
        }
        mArticleList = articleList
    }

    /**
     * 更新UI视图
     */
    private fun updateUI() {
        // 在这里更新UI视图
        // 设置布局和适配器
        val layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = mAdapter
        mAdapter.setData(mArticleList)
    }
}